package com.leoman.controller.api;

import com.leoman.core.ErrorType;
import com.leoman.core.bean.Result;
import com.leoman.entity.Letter;
import com.leoman.exception.*;
import com.leoman.service.LetterMoneyService;
import com.leoman.service.LetterService;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 信件api
 * Created by 涂奕恒 on 2016/11/28 0018.
 */
@Controller
@RequestMapping(value = "api/letter")
public class LetterApi {

    @Autowired
    private LetterService letterService;

    @Autowired
    private LetterMoneyService letterMoneyService;

    /**
     * @api {post} /api/letter/list 1、信件列表
     * @apiVersion 0.0.1
     * @apiName letter.list
     * @apiGroup letter
     *
     * @apiDescription 信件列表
     *
     * @apiParam   {Integer}   userId                     用户Id
     * @apiParam   {Integer}   type                       类型，1=花草丛，2=天涯，3=身边
     * @apiParam   {Integer}   isMe                       类别，1=我发的信，不填默认为0，即不是我发的信
     * @apiParam   {Integer}   pageNum                    页码
     * @apiParam   {Integer}   pageSize                   每页显示条数
     *
     * @apiSuccess {Object}    list
     * @apiSuccess {Integer}   list.id                    信件ID
     * @apiSuccess {Integer}   list.type                  类型，1=花草丛，2=天涯，3=身边
     * @apiSuccess {String}    list.title                 标题
     * @apiSuccess {String}    list.content               内容
     * @apiSuccess {Integer}   list.textCount             文字数
     * @apiSuccess {Integer}   list.imageCount            图片数
     * @apiSuccess {Integer}   list.praiseNum             点赞数
     * @apiSuccess {Integer}   list.commentNum            评论数
     * @apiSuccess {Integer}   list.getNum                打赏数
     * @apiSuccess {Integer}   list.isPraise              是否点赞，0=否，1=是
     * @apiSuccess {Integer}   list.isGet                 是否打赏，0=否，1=是
     * @apiSuccess {Integer}   list.isDraft               是否草稿，0=否，1=是
     * @apiSuccess {Integer}   list.userId                发送人ID
     * @apiSuccess {String}    list.nickName              发送人昵称
     * @apiSuccess {String}    list.avatar                发送人头像
     * @apiSuccess {String}    list.userName              发送人姓名
     * @apiSuccess {String}    list.mobile                发送人手机号
     * @apiSuccess {String}    list.address               发送人地址
     * @apiSuccess {Integer}   list.isHidden              是否匿名，0=否，1=是
     * @apiSuccess {Double}    list.openMoney             打开金额
     * @apiSuccess {Integer}   list.overCount             剩余收取次数
     * @apiSuccess {String}    list.createTime            发送时间
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "page": {
     *              "totalNum": 0,
     *              "totalPage": 0,
     *              "currentPage": 1
     *          },
     *          "list": [
     *              {
     *                  "id" : 1,
     *                  "type" : 1,
     *                  "title" : "信件",
     *                  "content" : "我是一只萌萌哒小兔子，我生长在美丽的帕斯...",
     *                  "textCount" : 100,
     *                  "imageCount" : 2,
     *                  "praiseNum" : 124,
     *                  "commentNum" : 20,
     *                  "getNum" : 20,
     *                  "isPraise" : 0,
     *                  "isGet" : 0,
     *                  "isDraft" : 0,
     *                  "userId" : 1,
     *                  "nickName" : "一只流浪的猫",
     *                  "avatar" : "http://4.16.3.22:8080/images/cover.jpg",
     *                  "userName" : "张三",
     *                  "mobile" : "15856325547",
     *                  "address" : "武汉市洪山区",
     *                  "isHidden" : 0,
     *                  "openMoney" : "1.5",
     *                  "overCount" : 8,
     *                  "createTime" : "1476843673494"
     *              }
     *          ]
     *      }
     * }
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public void list(HttpServletResponse response, Integer userId, Integer type, Integer isMe, Integer pageNum, Integer pageSize) {
        Page<Letter> page = letterService.iPageForApp(userId, type, isMe, pageNum, pageSize);
        Map<String, Object> dataMap = JsonUtil.fitting(page);
        String result = JsonUtil.obj2ApiJson(Result.successApi(dataMap), "user", "toUser", "stampId", "paperId", "mailerId", "printStatus", "imageList");
        WebUtil.printApi(response, result);
    }

    /**
     * @api {post} /api/letter/info 2、信件详情
     * @apiVersion 0.0.1
     * @apiName letter.info
     * @apiGroup letter
     *
     * @apiDescription 信件详情
     *
     * @apiParam   {Integer}   letterId                         信件Id       （必填）
     * @apiParam   {Integer}   userId                           用户ID
     *
     * @apiSuccess {Object}    letterInfo
     * @apiSuccess {Integer}   letterInfo.id                    信件ID
     * @apiSuccess {Integer}   letterInfo.type                  类型，1=花草丛，2=天涯，3=身边
     * @apiSuccess {String}    letterInfo.title                 标题
     * @apiSuccess {String}    letterInfo.content               内容
     * @apiSuccess {Integer}   letterInfo.textCount             文字数
     * @apiSuccess {Integer}   letterInfo.imageCount            图片数
     * @apiSuccess {Integer}   letterInfo.praiseNum             点赞数
     * @apiSuccess {Integer}   letterInfo.commentNum            评论数
     * @apiSuccess {Integer}   letterInfo.isPraise              是否点赞，0=否，1=是
     * @apiSuccess {Integer}   letterInfo.isDraft               是否草稿，0=否，1=是
     * @apiSuccess {Integer}   letterInfo.userId                发送人ID
     * @apiSuccess {String}    letterInfo.nickName              发送人昵称
     * @apiSuccess {String}    letterInfo.avatar                发送人头像
     * @apiSuccess {String}    letterInfo.userName              发送人姓名
     * @apiSuccess {String}    letterInfo.mobile                发送人手机号
     * @apiSuccess {String}    letterInfo.address               发送人地址
     * @apiSuccess {Integer}   letterInfo.isHidden              是否匿名，0=否，1=是
     * @apiSuccess {Double}    letterInfo.openMoney             打开金额
     * @apiSuccess {Double}    letterInfo.imageList             图片列表
     * @apiSuccess {Double}    letterInfo.imageList.id          图片id
     * @apiSuccess {Double}    letterInfo.imageList.url         图片url
     * @apiSuccess {String}    letterInfo.createTime            发送时间
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "page": {
     *              "totalNum": 0,
     *              "totalPage": 0,
     *              "currentPage": 1
     *          },
     *          "letterInfo": [
     *              {
     *                  "id" : 1,
     *                  "type" : 1,
     *                  "title" : "信件",
     *                  "content" : "我是一只萌萌哒小兔子，我生长在美丽的帕斯...",
     *                  "textCount" : 100,
     *                  "imageCount" : 2,
     *                  "praiseNum" : 124,
     *                  "commentNum" : 20,
     *                  "isPraise" : 0,
     *                  "isDraft" : 0,
     *                  "userId" : 1,
     *                  "nickName" : "一只流浪的猫",
     *                  "avatar" : "http://4.16.3.22:8080/images/cover.jpg",
     *                  "userName" : "张三",
     *                  "mobile" : "15856325547",
     *                  "address" : "武汉市洪山区",
     *                  "isHidden" : 0,
     *                  "openMoney" : "1.5",
     *                  "imageList" : [
     *                      {
     *                          "id" : 1,
     *                          "url" : "http://4.16.3.22:8080/images/cover.jpg"
     *                      },
     *                      {
     *                          "id" : 2,
     *                          "url" : "http://4.16.3.22:8080/images/cover.jpg"
     *                      }
     *                  ],
     *                  "createTime" : "1476843673494"
     *              }
     *          ]
     *      }
     * }
     */
    @RequestMapping(value = "/info", method = RequestMethod.POST)
    public void info(HttpServletResponse response, Integer userId, Integer letterId) {
        try {
            Letter letter = letterService.iFindOneForApp(userId, letterId);
            String result = JsonUtil.obj2ApiJson(Result.successInfoApi(letter, "letterInfo"), "user", "toUser", "stampId", "paperId", "mailerId", "printStatus", "overCount", "isGet");
            WebUtil.printApi(response, result);
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        } catch (LetterNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_LETTER_NOT_FIND));
        }
    }

    /**
     * @api {post} /api/letter/save 3、添加信件
     * @apiVersion 0.0.1
     * @apiName letter.save
     * @apiGroup letter
     *
     * @apiDescription 添加信件
     *
     * @apiParam   {Integer}   userId                用户Id                       （必填）
     * @apiParam   {Integer}   tempId                信件草稿ID
     * @apiParam   {Integer}   type                  类型，1=花草丛，2=天涯，3=身边   （必填）
     * @apiParam   {String}    title                 标题
     * @apiParam   {String}    content               内容
     * @apiParam   {Integer}   textCount             文字数量
     * @apiParam   {Integer}   stampId               邮票ID
     * @apiParam   {Integer}   paperId               信纸ID
     * @apiParam   {Integer}   mailerId              信封ID
     * @apiParam   {Integer}   sendType              发送方式，1=普通，2=快件，不填默认为1
     * @apiParam   {String}    userName              发送人姓名
     * @apiParam   {String}    mobile                发送人手机号
     * @apiParam   {String}    address               发送人地址
     * @apiParam   {Integer}   toUserId              接收人ID
     * @apiParam   {String}    toUserName            接收人姓名
     * @apiParam   {String}    toMobile              接收人手机号
     * @apiParam   {String}    toAddress             接收人地址
     * @apiParam   {Integer}   isHidden              是否匿名，0=否，1=是
     * @apiParam   {Double}    openMoney             打开金额
     * @apiParam   {Integer}   imgNum                图片数量
     * @apiParam   {Stream}    image                 图片组
     * @apiParam   {Integer}   isDraft               是否草稿，0=否，1=是       （必填）
     *
     * @apiSuccess {String}    letterId              信件ID
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "letterId" : 12
     *      }
     * }
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public void save(HttpServletResponse response,
                     Integer userId,
                     Integer tempId,
                     Integer type,
                     String title,
                     String content,
                     Integer textCount,
                     Integer stampId,
                     Integer paperId,
                     Integer mailerId,
                     Integer sendType,
                     String userName,
                     String mobile,
                     String address,
                     Integer toUserId,
                     String toUserName,
                     String toMobile,
                     String toAddress,
                     Integer isHidden,
                     String openMoney,
                     Integer imgNum,
                     Integer isDraft,
                     MultipartRequest multipartRequest) {
        try {
            Integer resultId = letterService.addLetterInfo(false,
                    userId,
                    tempId,
                    type,
                    title,
                    content,
                    textCount,
                    stampId,
                    paperId,
                    mailerId,
                    sendType,
                    userName,
                    mobile,
                    address,
                    toUserId,
                    toUserName,
                    toMobile,
                    toAddress,
                    isHidden,
                    openMoney,
                    imgNum,
                    isDraft,
                    multipartRequest);
            String result;

            if (resultId != 0) {
                result = JsonUtil.obj2ApiJson(Result.successInfoApi(resultId, "letterId"));
            } else {
                result = JsonUtil.obj2ApiJson(Result.successApi());
            }

            WebUtil.printApi(response, result);
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        }
    }

    /**
     * @api {post} /api/letter/draft 4、信件草稿
     * @apiVersion 0.0.1
     * @apiName letter.draft
     * @apiGroup letter
     *
     * @apiDescription 信件草稿
     *
     * @apiParam   {Integer}   userId                           用户Id               （必填）
     *
     * @apiSuccess {Object}    letterInfo
     * @apiSuccess {Integer}   letterInfo.id                    信件草稿ID
     * @apiSuccess {Integer}   letterInfo.type                  类型，1=花草丛，2=天涯，3=身边
     * @apiSuccess {String}    letterInfo.title                 标题
     * @apiSuccess {String}    letterInfo.content               内容
     * @apiSuccess {String}    letterInfo.userName              发送人姓名
     * @apiSuccess {String}    letterInfo.mobile                发送人手机号
     * @apiSuccess {String}    letterInfo.address               发送人地址
     * @apiSuccess {Integer}   letterInfo.isHidden              是否匿名，0=否，1=是
     * @apiSuccess {Double}    letterInfo.openMoney             打开金额
     * @apiSuccess {Double}    letterInfo.imageList             图片列表
     * @apiSuccess {Double}    letterInfo.imageList.id          图片id
     * @apiSuccess {Double}    letterInfo.imageList.url         图片url
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "letterInfo": {
     *              "id" : 1,
     *              "title" : "标题",
     *              "cover" : "http://www.qq.com",
     *              "content" : "我是一只萌萌哒小兔子，我生长在美丽的帕斯米尔大草原，我从小就喜欢吃青草",
     *              "imageList" : [
     *                  {
     *                      "id" : 1,
     *                      "url" : "http://www.qq.com",
     *                      "createTime" : "14956465135461"
     *                  }
     *              ],
     *              "openMoney" : 1.5
     *          }
     *      }
     * }
     */
    @RequestMapping(value = "/draft", method = RequestMethod.POST)
    public void draft(HttpServletResponse response, Integer userId) {
        try {
            Letter letter = letterService.iFindDraftByUserId(userId);
            String result = JsonUtil.obj2ApiJson(Result.successInfoApi(letter, "letterInfo"), "isDraft", "printStatus", "mailerId", "paperId", "stampId", "user", "textCount", "imageCount", "praiseNum", "commentNum", "isPraise", "isCollect", "isAdmin", "userId", "nickName", "avatar", "overCount", "createTIme");
            WebUtil.printApi(response, result);
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, JsonUtil.obj2ApiJson(Result.failureApi(ErrorType.ERROR_NOT_PARAM)));
        } catch (NoDataException e) {
            WebUtil.printApi(response, JsonUtil.obj2ApiJson(Result.failureApi(ErrorType.ERROR_NO_DATA)));
        }
    }

    /**
     * @api {post} /api/letter/listPlus 5、我的打赏信件列表or我的收信列表
     * @apiVersion 0.0.1
     * @apiName letter.listPlus
     * @apiGroup letter
     *
     * @apiDescription 我的打赏信件列表or我的收信列表
     *
     * @apiParam   {Integer}   userId                     用户Id
     * @apiParam   {Integer}   type                       类型，1=我的打赏信件列表 2、我的收信列表
     * @apiParam   {Integer}   pageNum                    页码
     * @apiParam   {Integer}   pageSize                   每页显示条数
     *
     * @apiSuccess {Object}    list
     * @apiSuccess {Integer}   list.id                    信件ID
     * @apiSuccess {Integer}   list.type                  类型，1=花草丛，2=天涯，3=身边
     * @apiSuccess {String}    list.title                 标题
     * @apiSuccess {String}    list.content               内容
     * @apiSuccess {Integer}   list.textCount             文字数
     * @apiSuccess {Integer}   list.imageCount            图片数
     * @apiSuccess {Integer}   list.praiseNum             点赞数
     * @apiSuccess {Integer}   list.commentNum            评论数
     * @apiSuccess {Integer}   list.isPraise              是否点赞，0=否，1=是
     * @apiSuccess {Integer}   list.isGet                 是否打赏，0=否，1=是
     * @apiSuccess {Integer}   list.userId                发送人ID
     * @apiSuccess {String}    list.nickName              发送人昵称
     * @apiSuccess {String}    list.avatar                发送人头像
     * @apiSuccess {String}    list.userName              发送人姓名
     * @apiSuccess {String}    list.mobile                发送人手机号
     * @apiSuccess {String}    list.address               发送人地址
     * @apiSuccess {Integer}   list.isHidden              是否匿名，0=否，1=是
     * @apiSuccess {Integer}   list.moneyStatus           是否付款，0=否，1=是
     * @apiSuccess {Double}    list.openMoney             打开金额
     * @apiSuccess {Integer}   list.overCount             剩余收取次数
     * @apiSuccess {Integer}   list.expressName           快递公司
     * @apiSuccess {Integer}   list.expressNum            快递单号
     * @apiSuccess {String}    list.createTime            发送时间
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "page": {
     *              "totalNum": 0,
     *              "totalPage": 0,
     *              "currentPage": 1
     *          },
     *          "list": [
     *              {
     *                  "id" : 1,
     *                  "type" : 1,
     *                  "title" : "信件",
     *                  "content" : "我是一只萌萌哒小兔子，我生长在美丽的帕斯...",
     *                  "textCount" : 100,
     *                  "imageCount" : 2,
     *                  "praiseNum" : 124,
     *                  "commentNum" : 20,
     *                  "isPraise" : 0,
     *                  "isGet" : 0,
     *                  "userId" : 1,
     *                  "nickName" : "一只流浪的猫",
     *                  "avatar" : "http://4.16.3.22:8080/images/cover.jpg",
     *                  "userName" : "张三",
     *                  "mobile" : "15856325547",
     *                  "address" : "武汉市洪山区",
     *                  "isHidden" : 0,
     *                  "openMoney" : "1.5",
     *                  "overCount" : 8,
     *                  "expressName" : "",
     *                  "expressNum" : "",
     *                  "createTime" : "1476843673494"
     *              }
     *          ]
     *      }
     * }
     */
    @RequestMapping(value = "/listPlus", method = RequestMethod.POST)
    public void listPlus(HttpServletResponse response, Integer userId, Integer type, Integer pageNum, Integer pageSize) {
        Page<Letter> page = letterService.iPagePlusForApp(userId, type, pageNum, pageSize);
        Map<String, Object> dataMap = JsonUtil.fitting(page);
        String result = JsonUtil.obj2ApiJson(Result.successApi(dataMap), "user", "stampId", "paperId", "mailerId", "printStatus", "imageList");
        WebUtil.printApi(response, result);
    }

    /**
     * @api {post} /api/letter/get 6、接收信件
     * @apiVersion 0.0.1
     * @apiName letter.get
     * @apiGroup letter
     *
     * @apiDescription 接收信件
     *
     * @apiParam   {Integer}   userId                用户Id                       （必填）
     * @apiParam   {Integer}   letterId              信件ID                       （必填）
     * @apiParam   {String}    userName              收信人姓名                    （必填）
     * @apiParam   {String}    mobile                收信人手机号                  （必填）
     * @apiParam   {String}    address               收信人地址                    （必填）
     * @apiParam   {Integer}   stampId               邮票ID                       （必填）
     * @apiParam   {Integer}   paperId               信纸ID                       （必填）
     * @apiParam   {Integer}   mailerId              信封ID                       （必填）
     * @apiParam   {Integer}   sendType              收信方式，1=普通，2=快件       （必填）
     *
     * @apiSuccess {String}    letterAcceptId        信件接收ID，当寄出的信件是身边人时返回
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "letterAcceptId" : 12
     *      }
     * }
     */
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    public void get(HttpServletResponse response,
                    Integer userId,
                    Integer letterId,
                    String userName,
                    String mobile,
                    String address,
                    Integer stampId,
                    Integer paperId,
                    Integer mailerId,
                    Integer sendType) {
        try {
            Integer resultId = letterService.getLetterInfo(userId, letterId, userName, mobile, address, stampId, paperId, mailerId, sendType);
            String result;

            if (resultId != 0) {
                result = JsonUtil.obj2ApiJson(Result.successInfoApi(resultId, "letterAcceptId"));
            } else {
                result = JsonUtil.obj2ApiJson(Result.successApi());
            }

            WebUtil.printApi(response, result);
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        } catch (UserNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_NOT_FIND));
        } catch (UserSealStatusException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_STATUS_DISABLED));
        } catch (LetterNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_LETTER_NOT_FIND));
        } catch (LetterAcceptCountMaxException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_LETTER_ACCEPT_COUNT_MAX));
        }
    }

    /**
     * @api {post} /api/letter/money 7、打赏信件（拆信）
     * @apiVersion 0.0.1
     * @apiName letter.money
     * @apiGroup letter
     *
     * @apiDescription 打赏信件（拆信）
     *
     * @apiParam   {Integer}   userId                用户Id                   （必填）
     * @apiParam   {Integer}   letterId              信件Id                   （必填）
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "userMoneyId" : 1
     *      }
     * }
     */
    @RequestMapping(value = "/money", method = RequestMethod.POST)
    public void money(HttpServletResponse response, Integer letterId, Integer userId) {
        try {
            Integer num = letterMoneyService.getMoneyLetter(userId, letterId);
            String result = JsonUtil.obj2ApiJson(Result.successInfoApi(num, "userMoneyId"));
            System.out.println();
            WebUtil.printApi(response, result);
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        }
    }
}
